const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}


// const baseurl='http://140.143.196.200:8000/api';
const baseurl='https://www.bdjsbffile.cn/api';
// const baseurl='http://192.168.31.17:65415/api';

//定时刷新token
let tokenRefreshTimer = null;

// 刷新token
const refreshToken = () => {
  return new Promise((resolve, reject) => {
    // 获取当前保存的用户信息
    let userInfo = wx.getStorageSync('userInfo') || {};
    
    if (!userInfo.token) {
      return reject('没有找到用户token');
    }
    
    // 调用刷新token接口
    wx.request({
      url: `${baseurl}/User/RefreshToken`, // 替换为实际的刷新token接口
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Username':userInfo.username,
        'Userrole':userInfo.role,
        'Uid':userInfo.userid,
        'Authorization':userInfo.token
    },
      success: (res) => {
        if (res.statusCode === 200 && res.data.token) {
          // 更新token
          userInfo.token = res.data.token;
          
          // 更新本地缓存
          wx.setStorageSync('userInfo', userInfo);
          console.log('Token已刷新并更新到本地缓存', new Date());
          resolve(res.data);
        } else {
          console.error('刷新token失败:', res);
          reject(res);
        }
      },
      fail: (error) => {
        console.error('刷新token请求失败:', error);
        reject(error);
      }
    });
  });
};

// 开始定时刷新token (每30分钟)
const startTokenRefresh = () => {
  if (tokenRefreshTimer) {
    clearInterval(tokenRefreshTimer);
  }
  
  // 先执行一次刷新
  refreshToken().catch(err => {
    console.error('初始刷新token失败:', err);
  });
  
  // 设置定时器，每30分钟执行一次
  tokenRefreshTimer = setInterval(() => {
    refreshToken().catch(err => {
      console.error('定时刷新token失败:', err);
    });
  }, 30 * 60 * 1000); // 30分钟
  
  console.log('已启动token定时刷新 (30分钟/次)');
  return tokenRefreshTimer;
};

// 停止定时刷新token
const stopTokenRefresh = () => {
  if (tokenRefreshTimer) {
    clearInterval(tokenRefreshTimer);
    tokenRefreshTimer = null;
    console.log('已停止token定时刷新');
  }
};

module.exports = {
  formatTime,
  baseurl,
  refreshToken,
  startTokenRefresh,
  stopTokenRefresh
}